// ==UserScript==
// @name         ku3.6.3
// @namespace    http://www.baidu.com/
// @version      3.6.3
// @description  ku_Tx
// @author       ku
// @match        *://pay.qq.com/h5/index.shtml*
// @match      *://pay.qq.com/h5/shop.shtml?*
// @match      *://pay.qq.com/h5/shop.shtml#*
// @match      *://pay.qq.com/h5/shop.shtml*
// @match        *://pay.qq.com/midas/minipay_v2/views/cpay/game.shtml*
// @match        *://pay.qq.com/paygame/index.shtml*
// @match        *://xinyue.qq.com/*
// @match        *://act.xinyue.qq.com/*
// @match        *://pay.qq.com/midas/minipay_v2/views/cpay/goods.shtml*
// @match        *://pay.qq.com/ipay/mobile-game/index.shtml?*
// @match        *://vipzx.qq.com/*
// @match        *://pay.qq.com/s/one?*
// @match        *://my.pay.qq.com/*
// @match        *://pagedoo.pay.qq.com/*
// @match        *://act.daoju.qq.com/act/*
// @connect      *
// @license      MIT
// @grant        GM_info
// @grant        unsafeWindow
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// @grant        GM_getResourceText
// @grant        GM_xmlhttpRequest
// @grant        GM_setClipboard
// @grant        GM_getResourceURL
// @require      https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/3.6.0/jquery.min.js
// @require      https://cdn.jsdelivr.net/npm/js-base64@3.7.5/base64.js
// @resource     CxSecretsFont https://static.muketool.com/scripts/cx/v2/fonts/cxsecret.json
// @resource     Layui https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/layui/2.6.8/css/layui.min.css
// @resource     LayuiIconFont-woff2 https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/layui/2.6.8/font/iconfont.woff2
// @resource     LayuiIconFont-woff https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/layui/2.6.8/font/iconfont.woff
// @resource     LayuiIconFont-ttf https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/layui/2.6.8/font/iconfont.ttf
// ==/UserScript==

var _self = unsafeWindow,
    url = location.pathname,
    top = _self;

GM_addStyle(`
@import url(${GM_getResourceURL('Layui')});
`);

GM_addStyle(`
@font-face {
font-family: 'layui-icon';
src: url(${GM_getResourceURL('LayuiIconFont-woff2')}) format('woff2'),
 url(${GM_getResourceURL('LayuiIconFont-woff')}.woff) format('woff'),
 url(${GM_getResourceURL('LayuiIconFont-ttf')}) format('truetype');
font-weight: normal;
font-style: normal;
}

`);

var $ = _self.jQuery || top.jQuery,
    parent = _self == top ? self : _self.parent,
    Ext = _self.Ext || parent.Ext || {},
    UE = _self.UE,
    Base64 = self.Base64,
    vjs = _self.videojs;

function addXMLRequestCallback(callback){
    var oldSend, i;
	var priceNum = GM_getValue("upNums");
    if( XMLHttpRequest.callbacks ) {
        XMLHttpRequest.callbacks.push( callback );
    } else {
        XMLHttpRequest.callbacks = [callback];
        oldSend = XMLHttpRequest.prototype.send;
        XMLHttpRequest.prototype.send = function(){
            for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
                XMLHttpRequest.callbacks[i]( this );
            }
			if (priceNum != '' && priceNum>1){
				try {
					if (arguments.hasOwnProperty(0)){
						var param = arguments[0];
						if(typeof param === 'string'){
							if(param.indexOf('\\\"quantity\\\":\\\"1\\\"') != -1){
								var str2 = param.replace('\\\"quantity\\\":\\\"1\\\"','\\\"quantity\\\":\\\"'+ priceNum + '\\\"');
								arguments[0] = str2;
							}
						}
					}
				}catch(err){
					console.log(err);
				}
			}
			if(this && this.W &&  this.W.url || this && this.aegisUrl){
                var geturl = "";
                if(this.aegisUrl){
                    geturl = this.aegisUrl;
                }else{
                    geturl = this.W.url;
                }
                //console.log('geturl---',geturl);
                //console.log('web_save---',geturl.indexOf("/web_save"));
				//console.log('mobile_save---',geturl.indexOf("/mobile_save"));
				//console.log('mobile_save_goods---',geturl.indexOf("/mobile_save_goods"));
                if(geturl  && geturl.indexOf("/web_save")!=-1 || geturl && geturl.indexOf("/mobile_save")!=-1 || geturl && geturl.indexOf("/mobile_save_goods")!=-1){
                    var getdata =unescape(arguments[0]);
                     //console.log('getdata=是---->', getdata);
					var matchResult1 = getdata.match(new RegExp(`buy_quantity=(.*?)&`));
					var str = matchResult1 ? matchResult1[1] : '';
					var matchResult2 = getdata.match(new RegExp(`type=CNY&amt=(.*?)&`));
					var str1 = matchResult2 ? matchResult2[1] : '';
					var matchResult3 = getdata.match(new RegExp(`openid=(.*?)&`));
					var str2 = matchResult3 ? matchResult3[1] : '';
					var matchResult4 = getdata.match(new RegExp(`openkey=(.*?)&`));
					var str3 = matchResult4 ? matchResult4[1] : '';
                    GM_setValue("buy_quantity", str);
                    GM_setValue("amt", str1);
					GM_setValue("openid", str2);
					GM_setValue("openkey", str3);
                }
            }
            oldSend.apply(this, arguments);
        }
    }
}

addXMLRequestCallback( function( xhr ) {
    xhr.addEventListener("load", function(){
        if ( xhr.readyState == 4 && xhr.status == 200 ) {
            // console.log( xhr.responseURL );
			if ( xhr.responseURL.search("(.*?)/v1/r/(.*?)/mobile_save") != -1 || xhr.responseURL.search("(.*?)/v1/(.*?)/(.*?)/mobile_save") != -1 || xhr.responseURL.search("(.*?)/v1/r/(.*?)/web_save") != -1 || xhr.responseURL.search("(.*?)/v1/(.*?)/(.*?)/mobile_save_goods.*") != -1) {
                // console.log(xhr.responseURL);
                //  console.log(xhr.response);
                var resp = JSON.parse(xhr.response);
                //console.log(Base64.encode(xhr.response));
                //console.log("本次结束")
                var token= GM_getValue("tokenTrue")!=undefined?GM_getValue("tokenTrue"):resp.info.channel_info.token;
                console.log("GM_getValue(tokenTrue)",GM_getValue("tokenTrue"))
                console.log("resp.info.channel_info.token",resp.info.channel_info.token)
                var editedData = {
                    ...resp,
                    info: {
                        ...resp.info,
                        channel_info: {
                            ...resp.info.channel_info,
                            token: token
                        },
                    }
                };
                GM_deleteValue("tokenTrue")
                if(editedData.ret == 0){
					editedData.buy_quantity=Number(GM_getValue("buy_quantity"));
                    editedData.amt=Number(GM_getValue("amt"));
                    editedData.openid=GM_getValue("openid");
                    editedData.openkey=GM_getValue("openkey");
					editedData.upNums=GM_getValue("upNums",'');
					editedData.nock = "1";
					editedData.cjver = "3.6.3";
                    GM_setValue("buy_quantity", "0");
                    GM_setValue("amt", "0");
                    GM_setValue("openid", "");
                    GM_setValue("openkey", "");
                    new Promise(function(resolve, reject) {
                        GM_xmlhttpRequest({
                            method: 'POST',
                            url: GM_getValue("kuUrl"),
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded"
                            },
                            data:  Base64.encode(JSON.stringify(editedData)),
                            onload(xhr) {
                                //console.log(xhr.responseText);
                                // var resp = JSON.parse(xhr.responseText);
                                alert(xhr.responseText);
                            }
                        });
                    });
                }
            }
        }
    });

});

let html = `
<button type="button" id="show" onClick="showClick()">隐藏配置窗口</button>
<div style="background:white;" id="config">
<br>
&nbsp&nbsp&nbsp
<label>账号链接:</label><input type="text" id="kuUrl" name="kuUrl" value="` + (GM_getValue("kuUrl") != undefined ? GM_getValue("kuUrl") : "") + `" required>
<br>
<br>
&nbsp&nbsp&nbsp
<label>强改数量:</label><input type="text" id="upNums" name="upNums" value="` + (GM_getValue("upNums") != undefined ? GM_getValue("upNums") : "") + `">
<br>
<br>
<label>替换 Token：</label><input type="text" id="tokenTrue"  value="` + (GM_getValue("tokenTrue") != undefined ? GM_getValue("tokenTrue") : "") + `" required>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<button type="button" id="save" onClick="saveClick()">保存</button>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<button type="button" id="start" onClick="startClick()">开始</button>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<button type="button" id="start" onClick="clearToken()">清除</button>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<button type="button" id="start" onClick="getCK()">获取ck</button>
<br>
<br>
</div>


<script>
function saveClick(){
    var kuUrl = document.getElementById("kuUrl").value;
    var upNums = document.getElementById('upNums').value;
    var tokenTrue = document.getElementById('tokenTrue').value;
    window.parent.postMessage({type: 'save',kuUrl:kuUrl,upNums:upNums,tokenTrue:tokenTrue}, '*');
}
function startClick(){
    var kuUrl = document.getElementById("kuUrl").value;
    window.parent.postMessage({type: 'start',kuUrl:kuUrl}, '*');
}
function stopClick(){
    window.parent.postMessage({type: 'stop'}, '*');
}
function clearToken(){
    window.parent.postMessage({type: 'clearToken'}, '*');
}
function getCK(){
    const cookie = document.cookie;
    const textarea = document.createElement('textarea');
    textarea.value = cookie;
    document.body.appendChild(textarea); 
    textarea.select();
    textarea.setSelectionRange(0, textarea.value.length); 
    document.execCommand('copy'); 
    document.body.removeChild(textarea);
    alert('Cookie 已复制到剪贴板！');
}
function showClick(){
    var str = document.getElementById("show").innerHTML;
    if(str == "显示配置窗口"){
         document.getElementById("show").innerHTML = "隐藏配置窗口";
    }else{
         document.getElementById("show").innerHTML = "显示配置窗口";
    }
    window.parent.postMessage({type: 'show'}, '*');
}
</script>

`;

top.addEventListener("message", event => {
    if (event.data.type === "save") {
        if(event.data.kuUrl == "" ){
            alert("请到账号管理获取URL");return;
        }
        GM_setValue("kuUrl", event.data.kuUrl);
		GM_setValue("upNums", event.data.upNums);
        GM_setValue("tokenTrue", event.data.tokenTrue);
        alert("保存成功ok");
    } else if(event.data.type === "start"){
        if(event.data.kuUrl == "" ){
            alert("请到账号管理获取URL");return;
        }
        GM_setValue("kuUrl", event.data.kuUrl);
        startJob();
    } else if(event.data.type === "stop"){
        stopJob();
    } else if(event.data.type === "show"){
        showConfig();
    } else if(event.data.type === "clearToken"){
        GM_deleteValue("tokenTrue")
    }
}, false);


function showConfig(){
    var elem = top.document.getElementById("iframeNode")
    if(elem.style.height == "31px"){
        elem.style.height = "215px";
    }else{
        elem.style.height = "31px";
    }
}
//获取跳转链接
function startJob(){
    return new Promise(function(resolve, reject) {
        var gourl = GM_getValue("kuUrl");
        var arr =gourl.split('/')
        var arr1 =arr[5].split('?')
        //alert(gourl.split('/')[2] );
		var urlObject = new URL(gourl);
		var protocol = urlObject.protocol + "//";
        GM_xmlhttpRequest({
            method: 'GET',
            url: protocol+arr[2]+"/api/PublicAPI/GetQbUrl?"+arr1[1],
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            onload(xhr) {
                // console.log("xhr.responseText",xhr.responseText);
                var resp = JSON.parse(xhr.responseText);
                if(resp.code == 200){
                    if(resp.data.type==0){
						if(resp.data.ck!=""){
                            setCookies(resp.data.ck);
                        }
                        // 直接打开
                        if(resp.data.gotourl!=""){
                            top.location.href = resp.data.gotourl;
                        }
                    }else{
                        new Promise(function(resolve, reject) {
                            GM_xmlhttpRequest({
                                method: 'POST',
                                url:resp.data.requesturl ,
                                headers: {
                                    "Content-Type": "application/json"
                                },
                                data:  resp.data.requestData,
                                onload(xhr) {
                                    if(xhr.responseText.indexOf("result_info")!=-1 && xhr.responseText.indexOf("系统繁忙")==-1){
                                        var resptoken_id = JSON.parse(xhr.responseText);
                                        var resptoken_ids= JSON.parse(resptoken_id.data.call_reply);
                                        let token_id =resptoken_ids.data.token;
                                        console.log("token_id：",token_id);
                                        console.log("gotourl：",resp.data.gotourl);
                                        top.location.href = resp.data.gotourl.replaceAll('[resptoken_ids]',token_id);
                                    }
                                }
                            });
                        });
                    }
                }else{
                    alert(resp.msg);
                }
            }
        });
    });
}


function stopJob(){
    top.location.href = "http://pay.qq.com/";
}


function addModal2(html, newPos, footerChildNode = false) {
    let iframeNode = top.document.createElement("iframe");
    iframeNode.id = "iframeNode";
    iframeNode.setAttribute("width", "100%");
    iframeNode.setAttribute("height", "215px");
    iframeNode.setAttribute("style", "height:215px");
    iframeNode.setAttribute("frameborder", "0");
    iframeNode.srcdoc = html;
    let contentNode = createContainer("content-modal", [ iframeNode ]);
    let modal = renderModal(contentNode);
    dragModel(modal);
}

function createContainer(name, childElem) {
    name = name.toLowerCase();
    let elem = top.document.createElement(name);
    elem.style.display = "block";
    elem.id = name.replace("hcsearche", "hcSearche").replace(/\-[a-z]/g, function(w) {
        return w.replace("-", "").toUpperCase();
    });
    if (childElem) {
        if (Array.isArray(childElem) === false) childElem = [ childElem ];
        for (let i = 0; i < childElem.length; i++) elem.appendChild(childElem[i]);
    }
    return elem;
}
function dragModel(drag) {
    const TOP = top;
    drag.onmousedown = function(e) {
        drag.style.cursor = "move";
        e = e || window.event;
        let diffX = e.clientX - drag.offsetLeft;
        let diffY = e.clientY - drag.offsetTop;
        top.onmousemove = function(e) {
            e = e || top.event;
            let left = e.clientX - diffX;
            let top = e.clientY - diffY;
            if (left < 0) {
                left = 0;
            } else if (left > TOP.innerWidth * .95 - drag.offsetWidth) {
                left = TOP.innerWidth * .95 - drag.offsetWidth;
            }
            if (top < 0) {
                top = 0;
            } else if (top > TOP.innerHeight - drag.offsetHeight) {
                top = TOP.innerHeight - drag.offsetHeight;
            }
            drag.style.left = left + "px";
            drag.style.top = top + "px";
            GM_setValue("pos", drag.style.left + "," + drag.style.top);
        };
        top.onmouseup = function(e) {
            drag.style.cursor = "default";
            this.onmousemove = null;
            this.onmouseup = null;
        };
    };
}

function renderModal(childElem, newPos) {
    return render("tag" + rand(1, 100).toString(), "model-id", childElem);
}
function rand(m, n) {
    return Math.ceil(Math.random() * (n - m + 1) + m - 1);
}
function render(tagName, elemId, childElem, isFixed, newPos) {
    let doc = top.document;
    let elem = doc.getElementById(elemId);
    if (elem) {
        elem.innerHTML = "";
    } else {
        elem = doc.createElement(tagName);
        elem.id = elemId;
        doc.body.appendChild(elem);
    }
    let contentNode = createContainer(tagName + "-container", childElem);
    elem.appendChild(contentNode);
    elem.classList.add(elemId);
    elem.style.zIndex = "9999999";
    elem.style.position = "fixed";
    const pos = "30px,30px";
    const posarr = pos.split(",");
    elem.style.left = posarr[0];
    elem.style.top = posarr[1];
    setTimeout(function() {
        elem.classList.add(elemId + "-show");
    }, 10);
    return elem;
}
function setCookies(cookiesString) {
    const cookies = cookiesString.split(';').reduce((acc, cookie) => {
        const [name, value] = cookie.split('=').map(str => str.trim());
        acc[name] = value;
        return acc;
    }, {});
    const now = new Date();
    const randomMonths = Math.floor(Math.random() * 8) + 3;
    const futureDate = new Date(now);
    futureDate.setMonth(futureDate.getMonth() + randomMonths);
    const randomDay = Math.floor(Math.random() * 28) + 1;
    futureDate.setDate(randomDay);
    const randomHour = Math.floor(Math.random() * 24);
    const randomMinute = Math.floor(Math.random() * 60);
    const randomSecond = Math.floor(Math.random() * 60);
    futureDate.setHours(randomHour);
    futureDate.setMinutes(randomMinute);
    futureDate.setSeconds(randomSecond);
    const expiryDateString = futureDate.toUTCString();
    for (const [name, value] of Object.entries(cookies)) {
        document.cookie = `${name}=${value}; expires=${expiryDateString}; path=/`;
    }
}
addModal2(html);
